<template>
	<view class="container">
		<!-- 搜索区域 -->
		<view class="search-box">
			<view class="search-bar">
				<uni-icons type="search" size="16" color="#666666"></uni-icons>
				<input 
					type="text" 
					class="search-input" 
					placeholder="搜索订单" 
					v-model="searchKey"
					@confirm="handleSearch"
					confirm-type="search"
				/>
				<uni-icons 
					v-if="searchKey" 
					type="clear" 
					size="16" 
					color="#999999" 
					@click="clearSearch"
				></uni-icons>
			</view>
			<!-- <view class="date-picker">
				<uni-datetime-picker
					type="daterange"
					v-model="dateRange"
					@change="handleDateChange"
					:clear-icon="false"
					:start="startDate"
					:end="endDate"
					rangeSeparator="至"
				>
					<view class="picker-trigger">
						<text>{{ dateRangeText }}</text>
						<uni-icons type="calendar" size="16" color="#666666"></uni-icons>
					</view>
				</uni-datetime-picker>
			</view> -->
		</view>
		
		<!-- 订单状态标签栏 -->
		<view class="tab-bar">
			<view 
				class="tab-item" 
				v-for="(item, index) in tabList" 
				:key="index"
				:class="{ active: currentTab === index }"
				@click="switchTab(index)"
			>
				<text>{{item.name}}</text>
				<text class="badge" v-if="item.count > 0">{{item.count}}</text>
			</view>
		</view>
		
		<!-- 订单列表 -->
		<scroll-view 
			scroll-y="true" 
			class="order-list"
			@scrolltolower="loadMore"
			:refresher-enabled="true"
			@refresherrefresh="refresh"
			:refresher-triggered="isRefreshing"
		>
			<view class="order-item" v-for="(order, index) in orderList" :key="index">
				<!-- 订单头部 -->
				<view class="order-header">
					<text class="order-no">订单号：{{order.orderNo}}</text>
					<text class="order-status">{{getStatusText(order)}}</text>
				</view>
				
				<!-- 商品信息 -->
				<view class="goods-info" @click="goOrderDetail(order)">
					<image 
						:src="order.goods[0].image" 
						mode="aspectFill" 
						class="goods-img"
					></image>
					<view class="goods-content">
						<view class="goods-title">{{order.goods[0].title}}</view>
						<view class="goods-price">
							<text class="price">￥{{order.goods[0].price}}</text>
							<text class="count">x{{order.goods[0].count}}</text>
						</view>
						<view class="gift-info" v-if="order.goods[0].giftNum > 0">
							<text class="tag">赠</text>
							<text>赠送 {{order.goods[0].giftNum}} 件</text>
						</view>
					</view>
				</view>
				
				<!-- 更多商品提示 -->
				<view class="more-goods" v-if="order.goods.length > 1">
					<text>共{{order.goods.length}}件商品</text>
					<uni-icons type="right" size="14" color="#999"></uni-icons>
				</view>
				
				<!-- 订单金额 -->
				<view class="order-amount">
					<text>实付款</text>
					<text class="amount">￥{{order.totalAmount}}</text>
				</view>
			</view>
			
			<!-- 空状态 -->
			<view class="empty" v-if="orderList.length === 0">
				<image src="/static/images/empty-goods.png" mode="aspectFit"></image>
				<text>暂无相关订单</text>
			</view>
			
			<!-- 加载更多 -->
			<view class="loading" v-if="orderList.length > 0">
				<text v-if="hasMore">加载更多...</text>
				<text v-else>没有更多了</text>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { config } from '@/utils/config.js'

// 添加管理员状态判断
const isAdmin = computed(() => uni.getStorageSync('userRole') === 2)

// 修改标签页列表
const tabList = ref([
	{ name: '全部', status: 0 },
	{ name: isAdmin.value ? '待送货' : '待收货', status: 1 },
	{ name: '已完成', status: 2 },
	{ name: '已取消', status: 3 }
])

// 当前选中的标签
const currentTab = ref(0)

// 订单列表
const orderList = ref([])

// 分页和加载状态
const page = ref(1)
const pageSize = 10
const hasMore = ref(true)
const isRefreshing = ref(false)
const loading = ref(false)

// 搜索相关
const searchKey = ref('')
const dateRange = ref([])
const startDate = computed(() => {
	const date = new Date()
	date.setMonth(date.getMonth() - 3) // 默认可选近3个月
	return date.toISOString().split('T')[0]
})
const endDate = computed(() => {
	return new Date().toISOString().split('T')[0]
})

// 日期显示文本
const dateRangeText = computed(() => {
	if (dateRange.value && dateRange.value.length === 2) {
		return `${dateRange.value[0]} 至 ${dateRange.value[1]}`
	}
	return '选择日期'
})

// ��理日期变化
const handleDateChange = (e) => {
	if (e && e.length === 2) {
		handleSearch()
	}
}

// 清除搜索条件
const clearSearch = () => {
	searchKey.value = ''
	dateRange.value = []
	handleSearch()
}

// 处理搜索
const handleSearch = () => {
	page.value = 1
	orderList.value = []
	hasMore.value = true
	getOrderList(true)
}

// 修改参数拼接辅助函数
const buildQueryString = (params) => {
	return Object.keys(params)
		.filter(key => params[key] !== undefined && params[key] !== '')
		.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
		.join('&');
};

// 修改获取订单列表方法
const getOrderList = async (isRefresh = false) => {
	if (loading.value || (!hasMore.value && !isRefresh)) return
	
	loading.value = true
	try {
		if (isRefresh) {
			page.value = 1
			hasMore.value = true
		}
		
		// 构建查询参数对象
		const params = {
			page: page.value,
			pageSize
		}
		
		// 只有在非"全部"标签时才添加status参数
		const status = tabList.value[currentTab.value].status
		if (status !== 0) {
			params.status = status
		}
		
		// 添加搜索参数
		if (searchKey.value) {
			params.keyword = searchKey.value
		}
		
		// 添加日期参数
		if (dateRange.value && dateRange.value.length === 2) {
			params.startDate = dateRange.value[0]
			params.endDate = dateRange.value[1]
		}
		
		// 构建完整URL
		const queryString = buildQueryString(params)
		const url = `/api/orders/list${queryString ? `?${queryString}` : ''}`
		
		const res = await uni.request({
			url: config.baseUrl + url,
			method: 'GET',
			header: {
				'Authorization': `Bearer ${uni.getStorageSync('token')}`
			}
		})
		
		if (res.data.code === 200) {
			const newList = res.data.data || []
			// 处理订单数据
			const processedList = newList.map(order => ({
				...order,
				goods: order.orderGoods.map(item => ({
					id: item.goodsId,
					title: item.goodsTitle,
					price: item.goodsPrice,
					count: item.num,
					giftNum: item.giftNum,
					giftRuleText: item.giftRuleText,
					image: item.goodsImage ? `${config.imageBaseUrl}${item.goodsImage}` : '/static/images/default-goods.png'
				})),
				totalAmount: order.total_price,
				statusText: getStatusText(order)
			}))
			
			if (isRefresh) {
				orderList.value = processedList
			} else {
				orderList.value = [...orderList.value, ...processedList]
			}
			
			hasMore.value = newList.length === pageSize
			if (hasMore.value) page.value++
		} else {
			throw new Error(res.data.message || '获取订单列表失败')
		}
	} catch (error) {
		console.error('获取订单列表失败:', error)
		uni.showToast({
			title: error.message || '获取订单列表失败',
			icon: 'none'
		})
	} finally {
		loading.value = false
		if (isRefresh) {
			isRefreshing.value = false
		}
	}
}

// 切换标签
const switchTab = (index) => {
	if (currentTab.value === index) return
	currentTab.value = index
	getOrderList(true)
}

// 下拉刷新
const refresh = () => {
	isRefreshing.value = true
	getOrderList(true)
}

// 加载更多
const loadMore = () => {
	if (!hasMore.value || loading.value) return
	getOrderList()
}

// 获取状态文本
const getStatusText = (order) => {
	if (isAdmin.value) {
    if (order.status === 1) {
      if (order.customerStatus) {
        return "客户已确认";
      }
      if (order.deliveryStatus) {
        return "已确认";
      }
	  return '待送货'
    }else if(order.status === 2){
      return '已完成'
    }else if(order.status === 3){
      return '已取消'
    }
  } else {
    if(order.status === 1){
		if (order.customerStatus) {
        return "我已确认";
      }
      if (order.deliveryStatus) {
        return "送货员已确认";
      }
	  else{
		return '待收货'
	  }
    }else if(order.status === 2){
      return '已完成'
    }else if(order.status === 3){
      return '已取消'
    }
  }
}

// 跳转到订单详情
const goOrderDetail = (order) => {
	uni.navigateTo({
		url: `/pages/order/detail?id=${order.id}`
	})
}

// 监听页面加载
onMounted(() => {
    // 获取页面参数
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const options = currentPage.options
    
    // 如果有 tab 参数，切换到对应标签
    if (options && options.tab !== undefined) {
        const tabIndex = parseInt(options.tab)
        if (!isNaN(tabIndex) && tabIndex >= 0 && tabIndex < tabList.value.length) {
            currentTab.value = tabIndex
        }
    }
    
    getOrderList(true)
    
    // 监听自定义更新事件
    uni.$on('orderListUpdate', () => {
        getOrderList(true)
    })
})

// 组件卸载时移除事件监听
onUnmounted(() => {
	uni.$off('orderListUpdate')
})
</script>

<style lang="scss">
.container {
	min-height: 100vh;
	background: #f7f8fa;
}

.search-box {
	background: #fff;
	padding: 20rpx;
	display: flex;
	gap: 20rpx;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 100;
	
	.search-bar {
		flex: 1;
		display: flex;
		align-items: center;
		background: #f7f8fa;
		border-radius: 32rpx;
		padding: 0 24rpx;
		height: 64rpx;
		
		.uni-icons {
			margin-right: 12rpx;
		}
		
		.search-input {
			flex: 1;
			height: 64rpx;
			font-size: 28rpx;
			color: #333;
			
			&::placeholder {
				color: #999;
			}
		}
	}
	
	.date-picker {
		min-width: 200rpx;
		height: 64rpx;
		
		.picker-trigger {
			height: 100%;
			background: #f7f8fa;
			border-radius: 32rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 0 24rpx;
			gap: 8rpx;
			
			text {
				font-size: 24rpx;
				color: #666;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				max-width: 160rpx;
			}
			
			&:active {
				background: darken(#f7f8fa, 5%);
			}
		}
	}
}

.tab-bar {
	display: flex;
	background: #fff;
	padding: 0 20rpx;
	position: fixed;
	top: 104rpx;
	left: 0;
	right: 0;
	z-index: 100;
	
	.tab-item {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 88rpx;
		position: relative;
		
		text {
			font-size: 28rpx;
			color: #333;
		}
		
		.badge {
			position: absolute;
			top: 10rpx;
			right: 50%;
			transform: translateX(20rpx);
			background: #ff6b81;
			color: #fff;
			font-size: 20rpx;
			height: 32rpx;
			min-width: 32rpx;
			padding: 0 6rpx;
			border-radius: 16rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		
		&.active {
			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 40rpx;
				height: 4rpx;
				background: #ff6b81;
				border-radius: 2rpx;
			}
			
			text {
				color: #ff6b81;
				font-weight: bold;
			}
		}
	}
}

.order-list {
	padding: 192rpx 20rpx 20rpx;
	box-sizing: border-box;
	height: 100vh;
}

.order-item {
	background: #fff;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
	padding: 20rpx;
	
	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #f5f5f5;
		
		.order-no {
			font-size: 24rpx;
			color: #999;
		}
		
		.order-status {
			font-size: 24rpx;
			color: #ff6b81;
		}
	}
	
	.goods-info {
		display: flex;
		padding: 20rpx 0;
		
		.goods-img {
			width: 160rpx;
			height: 160rpx;
			border-radius: 8rpx;
		}
		
		.goods-content {
			flex: 1;
			margin-left: 20rpx;
			
			.goods-title {
				font-size: 28rpx;
				color: #333;
				margin-bottom: 8rpx;
			}
			
			.goods-price {
				display: flex;
				justify-content: space-between;
				align-items: center;
				
				.price {
					font-size: 32rpx;
					color: #ff6b81;
					font-weight: bold;
				}
				
				.count {
					font-size: 24rpx;
					color: #999;
				}
			}
		}
	}
	
	.more-goods {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		padding: 10rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
		
		text {
			font-size: 24rpx;
			color: #999;
			margin-right: 10rpx;
		}
	}
	
	.order-amount {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		padding: 20rpx 0;
		
		text {
			font-size: 24rpx;
			color: #999;
			
			&.amount {
				font-size: 32rpx;
				color: #ff6b81;
				font-weight: bold;
				margin-left: 10rpx;
			}
		}
	}
}

.empty {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding-top: 200rpx;
	
	image {
		width: 240rpx;
		height: 240rpx;
		margin-bottom: 30rpx;
	}
	
	text {
		font-size: 28rpx;
		color: #999;
	}
}

.loading {
	text-align: center;
	padding: 30rpx 0;
	
	text {
		font-size: 24rpx;
		color: #999;
	}
}

.gift-info {
	margin-top: 8rpx;
	display: flex;
	align-items: center;
	
	.tag {
		background: #ff6b81;
		color: #fff;
		font-size: 20rpx;
		padding: 2rpx 8rpx;
		border-radius: 4rpx;
		margin-right: 8rpx;
	}
	
	text {
		font-size: 24rpx;
		color: #ff6b81;
	}
}
</style> 